package com.jh.paymentchannel.service;

import java.net.URI;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Objects;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifuquick.AES;

import cn.jh.common.tools.Log;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class JFQuickCallBackService {

	private static final Logger log = LoggerFactory.getLogger(JFQuickCallBackService.class);

	@Autowired
	Util util;

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;
	
	@Value("${jf.key}")
	private String Key;
	
	/*private static String Key = "UD1RDD194BDVDPCCUB56434C39EWZE98";*/

	//异步回调通知
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jf/notify_call")
	public void jfQuickPayNotifyCallback(HttpServletRequest request,HttpServletResponse response,
			@RequestParam String encryptData,
            @RequestParam String signature
			
	) throws Exception {
		
		  log.info("异步回调进来了");
		  String dataPlain = AES.decode(Base64.decodeBase64(encryptData),Key.substring(0,16));
		  log.info("消费回调：dataPlain: {} " ,dataPlain);
		  String checkSign = DigestUtils.sha1Hex(encryptData + Key.substring(16));

		  log.info("消费回调：checkSign: {} " , checkSign);

		  
		  
		  if(!Objects.equal(signature,checkSign)){
		         log.error("签名验证失败");
		  }
		  
		  com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(dataPlain);
		  log.info("parseObject==========="+parseObject);
		  
		  com.alibaba.fastjson.JSONObject jsonObject2 = parseObject.getJSONObject("head");
		  
		  String workId = jsonObject2.getString("workId");
		  log.info("workId======"+workId);
		  String respCode = jsonObject2.getString("respCode");
		  log.info("respCode======"+respCode);
		  String orderId = parseObject.getString("orderId");
		  log.info("orderId======"+orderId);
		  String txnAmt = parseObject.getString("txnAmt");
		  log.info("txnAmt======"+txnAmt);
		  
			 
		  try {
				Log.setLogFlag(true);
				Log.println("---交易： 订单结果异步通知-------------------------");

				log.info("交易： 订单结果异步通知===================");
				if("success".equals(respCode)){ // 订单已支付;

					// 1、检查Amount和商户系统的订单金额是否一致
					// 2、订单支付成功的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理）；
					// 3、返回响应内容

					synchronized (this) {
						// **更新订单状态*//*
						// **调用下单，需要得到用户的订单信息*//*
						RestTemplate restTemplate = new RestTemplate();

						URI uri = util.getServiceUrl("transactionclear", "error url request!");
						String url = uri.toString() + "/v1.0/transactionclear/payment/update";

						// **根据的用户手机号码查询用户的基本信息*//*
						MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("status", "1");
						requestEntity.add("third_code", workId);
						requestEntity.add("order_code", orderId);
						String result = restTemplate.postForObject(url, requestEntity, String.class);

						log.info("订单状态修改成功===================");

						// **判断是否有外放的通道的处理， 如果有那么继续回调外放哦*//*
						uri = util.getServiceUrl("transactionclear", "error url request!");
						url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";

						requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("order_code", orderId);
						result = restTemplate.postForObject(url, requestEntity, String.class);

						JSONObject jsonObject = JSONObject.fromObject(result);
						JSONObject resultObj = jsonObject.getJSONObject("result");
						String outMerOrdercode = resultObj.getString("outMerOrdercode");
						String orderdesc = resultObj.getString("desc");
						String phone = resultObj.getString("phone");
						String tranamount = resultObj.getString("amount");
						String channelTag = resultObj.getString("channelTag");
						String notifyURL = resultObj.getString("outNotifyUrl");
						if (outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")) {
							uri = util.getServiceUrl("channel", "error url request!");
							url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
							requestEntity = new LinkedMultiValueMap<String, String>();
							requestEntity.add("merchant_no", phone);
							requestEntity.add("amount", tranamount);
							requestEntity.add("channel_tag", channelTag);
							requestEntity.add("order_desc", URLEncoder.encode(orderdesc, "UTF-8"));
							requestEntity.add("order_code", outMerOrdercode);
							requestEntity.add("sys_order", orderId);
							requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
							result = restTemplate.postForObject(url, requestEntity, String.class);
						}

						log.info("订单已支付!");
						response.getWriter().write("000000");
					}
				} else {
					// 1、订单支付失败的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理，避免成功后又修改为失败）；
					// 2、返回响应内容

					log.info("订单支付失败!");
				}
			} catch (Exception e) {
				log.error(e.getMessage());
			}
			log.info("-----处理完成----");
	}


	
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jf/return_call")
	public String jfQuickPayReturnCallback(HttpServletRequest request,HttpServletResponse response,
			@RequestParam String encryptData,
            @RequestParam String signature
			
	) throws Exception {
		
		  log.info("同步通知进来了");
		  String dataPlain = AES.decode(Base64.decodeBase64(encryptData),Key.substring(0,16));
		  log.info("同步通知：dataPlain: {} " ,dataPlain);
		  String checkSign = DigestUtils.sha1Hex(encryptData + Key.substring(16));

		  log.info("同步通知：checkSign: {} " , checkSign);

		  
		  
		  if(!Objects.equal(signature,checkSign)){
		         log.error("签名验证失败");
		  }
		  
		  com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(dataPlain);
		  log.info("parseObject==========="+parseObject);
		  
		  com.alibaba.fastjson.JSONObject jsonObject2 = parseObject.getJSONObject("head");
		  
		  String status = parseObject.getString("status");
		  log.info("status======"+status);
		  String respCode = jsonObject2.getString("respCode");
		  log.info("respCode======"+respCode);
		  String orderId = parseObject.getString("orderId");
		  log.info("orderId======"+orderId);
		  String txnAmt = parseObject.getString("txnAmt");
		  log.info("txnAmt======"+txnAmt);
		
		  if("success".equals(respCode)){
			  log.info("同步回调成功");
			  return "sdjsuccess";
		  }else{
			  log.info("同步回调失败");
			  return "sdjerror";
		  }
		
	}

}
